package com.takeaway.utils.myconnectionpool;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;

/**
 * @author 后台赖骏
 */
@SuppressWarnings("unused")
public class PoolAgent implements InvocationHandler {
    private Connection connection ;
    private MyDataBase myDataBase ;
    private final static String CLOSE = "close";

    public PoolAgent(Connection connection, MyDataBase myDataBase) {
        this.connection = connection;
        this.myDataBase = myDataBase;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (CLOSE.equals(method.getName())) {
            myDataBase.closeConnection(this);
            return null;
        } else {
            return method.invoke(connection, args);
        }
    }
    public Connection getAgent(){
        return (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(),
                new Class<?>[]{Connection.class},
                this);
    }

    public Connection getConnection() {
        return connection;
    }

    public void setConnection(Connection connection) {
        this.connection = connection;
    }

    public MyDataBase getMyDataBase() {
        return myDataBase;
    }

    public void setMyDataBase(MyDataBase myDataBase) {
        this.myDataBase = myDataBase;
    }
}
